package cn.uncode.springcloud.starter.canary.feign;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.uncode.springcloud.starter.canary.api.CanaryContext;
import cn.uncode.springcloud.starter.canary.api.CanaryStrategy;
import cn.uncode.springcloud.starter.canary.ribbon.support.RibbonContext;
import cn.uncode.springcloud.starter.canary.ribbon.support.RibbonContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * Feign统一Token拦截器
 */
@Slf4j
public class FeignCanaryInterceptor implements RequestInterceptor {
	
	@Autowired
	private CanaryContext canaryContext;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if(null==getHttpServletRequest()){
            log.error("HttpServletRequest对象为空");
            return;
        }
        //取header
        String canaryFlag = getHeaders(getHttpServletRequest()).get(CanaryStrategy.FEIGN_CANARY_HEAD_KEY);
        if(StringUtils.isNotBlank(canaryFlag)) {
        	RibbonContext ribbonContext = new RibbonContext();
        	ribbonContext.valueOf(canaryFlag);
        	RibbonContextHolder.setRibbonContext(ribbonContext);
    		requestTemplate.header(CanaryStrategy.FEIGN_CANARY_HEAD_KEY, ribbonContext.toString());
        }
    }
    
    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * Feign拦截器拦截请求获取Token对应的值
     * @param request
     * @return
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
    
}
